import sys, os
sys.path.append(os.path.abspath(
    os.path.join(os.path.dirname(__file__), os.path.pardir)
))
from typing import List
from datetime import datetime

from base_class import Flight, Position, PositionType, GuaranteeStep
from util.message import TIME_STR_PARSE_ERROR


def json_to_flight(data):
    fmt = "%Y-%m-%d %H:%M:%S"
    res = []
    empty_stand_list = []
    for flight in data:
        try:
            start_moment = datetime.strptime(flight["arrPlanLanding"], fmt) if flight["isArrFlight"] \
                else datetime.strptime(flight["depPlanTaskOff"], fmt)
            # else datetime.strptime(flight["depPlanTakeOff"], fmt)
        except:
            errMsg = TIME_STR_PARSE_ERROR
            time_str = flight["arrPlanLanding"] if flight["isArrFlight"] else flight["depPlanTaskOff"]
            errMsg["resultMessage"] = f"{time_str}(Flight ID: {flight['id']})"
            continue
            # return None, errMsg

        # 没有机位信息的航班无法分析，不通过筛选
        if flight["craftSeatFlight"]:
            fli = Flight(id=flight["id"],
                        flight_no=flight["flightNo"],
                        flight_date=start_moment.date(),
                        estimated_time=start_moment,
                        normal_cnt=flight["passengerCnt"],
                        vip_cnt=flight["vipCnt"],
                        priority=1, # 默认优先级１
                        is_arr=flight["isArrFlight"],
                        is_remote_stand=None,
                        remote_stand=Position(
                            pos_type=PositionType.Remote,  
                            name=flight["craftSeatFlight"]),    # 这里remote_stand包括所有机位
                        arrival_gate=None,
                        boarding_gate=None,
                        # raw_tasks=None
                        raw_tasks=flight["dispatchTaskDto"]
                    )
            res.append(fli)

        else:
            fli = Flight(id=flight["id"],
                    flight_no=flight["flightNo"],
                    flight_date=start_moment.date(),
                    estimated_time=start_moment,
                    normal_cnt=None,
                    vip_cnt=None,
                    priority=None,
                    is_arr=None,
                    is_remote_stand=None,
                    remote_stand=None,
                    arrival_gate=None,
                    boarding_gate=None,
                    raw_tasks=None
                )
            empty_stand_list.append(fli)

    res.sort(key=lambda x: x.estimated_time)

    return res, empty_stand_list

def parse_task_data(flights: List[Flight], dispatchId: int):
    tasks = []
    for f in flights:
        for t in f.raw_tasks:
            if t["dispatchId"] == dispatchId:
                tasks.append(t)

    return tasks